import router from "./router";
// import { useNProgress } from '@/hooks/useNProgress'
import { useCache } from "@/hooks/useCache";
import { TOKEN, TIME_STAMP } from "@/constant";
import { useUserStoreHook } from "@/store/modules/user";
import { usePublicStoreHook } from "@/store/modules/public";
// import { usePermissionSotreExternal } from '@/store/modules/permission'
// import { privateRoutes } from './router'

const { wsCache } = useCache();

const useStore = useUserStoreHook();
const publicStore = usePublicStoreHook();

// const { start, done } = useNProgress()
// 白名单
const whiteList = [
  "/login",
  "/screen/central",
  "/screen/page",
  "/screen/video",
  "/404",
];

/**
 * 路由前置守卫
 */
router.beforeEach(async (to, from, next) => {
  // start()
  if (to.path != "/login" && publicStore.collegeList.length == 0) {
    publicStore.getCollegeList();
    publicStore.getMajorList();
    publicStore.getGradeList();
    publicStore.getSocietyList();
  }
  if (wsCache.get(TOKEN)) {
    if (to.path === "/login") {
      next();
    } else {
      // 判断用户资料是否获取
      // 若不存在用户信息，则需要获取用户信息
      if (!useStore.getHasUerInfo) {
        try {
          const res = await useStore.getuserInfo();
          // // 处理用户权限，筛选出需要添加的权限
          // const filterRoutes = await usePermission.filterRoutes(privateRoutes, permissions)
          // // 利用 addRoute 循环添加
          // filterRoutes.forEach(item => {
          //   router.addRoute(item)
          // })
          // 添加完动态路由之后，需要在进行一次主动跳转

          // 根据role进行路由跳转，后续待完善 ----------------------------------------------------------------------------------------------------------------
          const role = res.data.role;
          if (role == 0 || role == 1) {
            return next(to.fullPath);
          } else {
            if (to.fullPath == "/screen/index") {
              next();
            } else {
              next("/manage/home");
            }
          }
        } catch (error) {
          // 删除 token，跳转登录页面
          useStore.resetToken();
          next("/login");
          // done()
        }
      } else {
        next();
      }
    }
  } else {
    // 没有 token 情况下可以进入白名单
    if (whiteList.indexOf(to.path) > -1) {
      next();
    } else {
      next("/login");
    }
  }
});

router.afterEach((to) => {
  // done() // 结束Progress
});
